package com.kma.ncpractice2013.servlets;

import com.kma.ncpractice2013.auth.Crypto;
import com.kma.ncpractice2013.dao.UserAccessLevelDAO;
import com.kma.ncpractice2013.dao.UserDAO;
import com.kma.ncpractice2013.dao.UserGroupDAO;
import com.kma.ncpractice2013.model.User;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * User: Viktor
 * Date: 11/9/13
 */
public class AdminServlet extends HttpServlet
{
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("application/json");
		//response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		String action = request.getParameter("action");



		if (action.equals("getUserList"))
		{
			String login = request.getParameter("login").length()>0?request.getParameter("login"):null;
			String name = request.getParameter("name").length()>0?request.getParameter("name"):null;
			String surname = request.getParameter("surname").length()>0?request.getParameter("surname"):null;
			Date startDate = request.getParameter("startdate").length()>0?Date.valueOf(request.getParameter("startdate")):null;
			Date endDate = request.getParameter("enddate").length()>0?Date.valueOf(request.getParameter("enddate")):null;
			int userGroup = Integer.parseInt(request.getParameter("usergroup"));
//			/int accessLevel = Integer.parseInt(request.getParameter("accesslevel"));
			int blockStatus = Integer.parseInt(request.getParameter("blocked"));
			out.print(getUserList(1, login, name, surname, startDate, endDate, userGroup,  blockStatus));
			response.flushBuffer();
		}
		else
		{

			if(action.equals("deleteUser"))
			{
				int id = Integer.parseInt(request.getParameter("id"));
				deleteUser(id);
				out.print(JSONObject.valueToString("User has been deleted"));

			}
			else
			if(action.equals("changeBlockedStatus"))
			{
				int id = Integer.parseInt(request.getParameter("id"));
				out.print(changeBlockStatus(id)); //returns action that can NOW be performed to user, displays on block button(block/unblock)

			}
			else
			if (action.equals("createUser"))
			{
				{

					String login = request.getParameter("login");
					String name = request.getParameter("name");
					String surname = request.getParameter("surname").length()>0?request.getParameter("surname"):null;
					Date birthDate = request.getParameter("birthdate").length()>0?Date.valueOf(request.getParameter("birthdate")):null;
					String password = request.getParameter("password");
					String phone = request.getParameter("phone").length()>0?request.getParameter("phone"):null;

					String userGroupStr = request.getParameter("usergroup");
					String accLevelStr = request.getParameter("accesslevel");
					if (!userGroupStr.matches("[2-3]$") || !accLevelStr.matches("[3-4]$"))
					{
						response.getWriter().print("Invalid input");
						return;
					}
					int userGroup = Integer.parseInt(userGroupStr);
					int accessLevel = Integer.parseInt(accLevelStr);

					if (!login.matches(".*[@].+"))
					{
						response.getWriter().print("Invalid input");
						return;
					}
					if (password.length()<8)
					{
						response.getWriter().print("Invalid input");
						return;
					}
					if (name.length()<4)
					{
						response.getWriter().print("Invalid input");
						return;
					}
					if (phone != null && !phone.matches("[0-9]{3,14}$"))
					{
						response.getWriter().print("Invalid input");
						return;
					}
					List<User> list = new ArrayList<User>();
					list.add(addUser(login, name, surname, userGroup, phone, accessLevel, password, birthDate));
					//response.flushBuffer();
					out.print(JSONObject.valueToString(list));
				}
			}
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		//doPost(request, response);
	}

	private String getUserList(int page, String login, String name, String surname, Date startDate, Date endDate, int userGroup, int blockStatus)
	{

		UserDAO userDAO = new UserDAO();
		List<User> userList = userDAO.search(login, name, surname, startDate, endDate, userGroup, blockStatus,0,10);

		UserGroupDAO groupDAO = new UserGroupDAO();
		UserAccessLevelDAO accessLevelDAO = new UserAccessLevelDAO();
		List<String> groupList = new ArrayList<String>();
		List<String> accessLevelList = new ArrayList<String>();
		for(User u:userList)
		{
			groupList.add(u.getGroupId().toString());
			accessLevelList.add(u.getAccessLevelId().toString());
		}


		HashMap<String, List> map = new HashMap<String, List>();
		map.put("grouplist", groupList);
		map.put("userlist", userList);
		map.put("accesslevellist", accessLevelList);


		return JSONObject.valueToString(map);


	}

	private void deleteUser(int id)
	{
		UserDAO userDAO = new UserDAO();
		userDAO.deleteById(id);
	}

	private String changeBlockStatus(int id)
	{
		UserDAO userDAO = new UserDAO();
		User user = userDAO.getById(id);
		user.setBlocked(user.getBlocked() == 1 ? 0 : 1);
		userDAO.update(user);

		return JSONObject.valueToString(user.getBlocked() == 1 ? "Unblock" : "Block");
	}

	private User addUser(String login, String name, String surname, int userGroup, String phone, int accessLevel, String password, Date birthDate)
	{
		String salt = Crypto.generateSalt();
		UserDAO userDAO= new UserDAO();
		User user = new User();
		user.setLogin(login);
		user.setBirthdate(birthDate);
		user.setName(name);
		user.setSurname(surname);
		user.setPhone(phone);
		user.setAccessLevelId(User.AccessLevel.getByValue(accessLevel));
		user.setGroupId(User.Group.getByValue(userGroup));
		user.setSalt(salt);
		user.setPassword(Crypto.getHash(salt, password, "SHA-256"));
		user.setRegistrationToken(UUID.randomUUID().toString());
		user.setRegistrationDate(new Date(System.currentTimeMillis()));
		user.setBlocked(0);
		userDAO.create(user);
		user = userDAO.getByLogin(login);
		return user;

	}
}
